import React, { Component } from 'react';
import { View,  Text, StyleSheet } from 'react-native';
import { List, InputItem, WhiteSpace, Button, WingBlank, Modal } from 'antd-mobile';
import { createForm } from 'rc-form';
import { dealerInfoAdd, smsPush } from '../../libs/api'
import HTTP from "../../libs/HTTP";
import SuccessResult from '../../widget/SuccessResult'
import color from '../../libs/color'
import md5 from "md5";


const alert = Modal.alert

function hasErrors(fieldsError) {
  return Object.keys(fieldsError).some(field => fieldsError[field]);
}

class RegisterForm extends Component {
  constructor(props) {
    super(props)
    this.state = {
      registerSuccess: false
    }
  }

  componentDidMount() {
    const params = this.props.navigation.state.params || {}
    this.phone = params['phone']
    this.props.form.validateFields();
  }

  render() {
    const { getFieldProps, getFieldsError, getFieldError } = this.props.form;
    return (
      <View style={styles.container}>
        {
          !this.state.registerSuccess && (
            <WingBlank>
              <WhiteSpace/>
              <List>
                <InputItem labelNumber={5} clear {
                  ...getFieldProps('companyName', {
                    rules: [
                      { required: true, message: '请输入公司名称' },
                    ]
                  })
                } error={!!getFieldError('companyName')} placeholder="请输入公司的名称" >公司名称 *</InputItem>
                <InputItem
                  error={!!getFieldError('realName')}
                  {...getFieldProps("realName", {
                      rules: [
                        { required: true, message: '请输入真实姓名' },
                      ]
                    }
                  )}
                  placeholder="请输入您的真实姓名">姓名 *</InputItem>
              </List>
              <WhiteSpace />
              <List>
                <InputItem type="password" error={!!getFieldError('password')} {...getFieldProps("password", {
                  rules: [
                    { required: true },
                  ]
                })} placeholder="请输入密码">密码 *</InputItem>
                <InputItem type="password" labelNumber={5} error={!!getFieldError('affirmPassword')} {...getFieldProps("affirmPassword", {
                  rules: [
                    { required: true },
                  ]
                })} placeholder="请再次输入密码">确认密码 *</InputItem>
              </List>
              <WhiteSpace />
              <Button type="primary" style={{borderRadius: 0}} disabled={hasErrors(getFieldsError())} onClick={this.submitRegister}>提交注册</Button>
            </WingBlank>
          )
        }
        {
          this.state.registerSuccess && (
            <SuccessResult message="注册成功，登陆账号将会短信发送到手机" onEnter={() => {this.props.navigation.navigate('Login')}}/>
          )
        }
      </View>
    )
  }
  submitRegister = () => {
    this.props.form.validateFields({ force: true }, (error) => {
      if (!error) {
        const values = this.props.form.getFieldsValue();
        if(values['affirmPassword'] !== values['password']) {
          alert('密码不一致')
          return false;
        } else {
          values['phone'] = this.phone
          console.log(values)
        }
        values['name'] = values['companyName']
        values['password'] = md5(values['password'])
        values['telephone'] = values['phone']
        HTTP.post(dealerInfoAdd(), values, () => {}, (resp) => {
          const params = JSON.stringify({"account": resp['organNo']})
          HTTP.post(smsPush(), {"mobile": this.phone, "domain": "winder", "signName": "winder科技", "templateCode": "SMS_113660108", params: params}, () => {}, (resp) => {
            this.setState({
              showNextStep: true,
              bizId: resp
            })
          })
          this.setState({
            registerSuccess: true
          })
        })
      } else {
        console.log(error)
        alert('提交校验失败');
      }
    });
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1
  }
})

const RegisterFormWrapper = createForm()(RegisterForm)

export default class Register extends Component {
  static navigationOptions = ({ navigation }) => ({
    title: '注册信息',
    headerTintColor: 'white',
    headerStyle:{ backgroundColor: color.theme},
    headerTitleStyle:{ color: 'white', fontSize: 20 },
  })

  constructor(props) {
    super(props)
  }

  render() {
    return (
      <RegisterFormWrapper {...this.props}/>
    )
  }
}

